/**
 * 把树形数据解包
 * @param {Array} treeData
 * @param {string} lowerKey
 * @param {Array} unpack
 * @returns {*[]}
 */
export function unpackTreeData(treeData, lowerKey = 'children', unpack = []) {
    if (treeData.length === 0) return [];
    for (let row of treeData) {
        let item = {...row}
        delete item[lowerKey]
        unpack.push(item);
        if (row[lowerKey] instanceof Array && row[lowerKey].length > 0) {
            unpack = unpackTreeData(row[lowerKey], lowerKey, unpack)
        }
    }
    return unpack
}


/**
 * 通过任意级的一个值获取树形数据完整值
 * @param {Array} treeData        tree数据
 * @param {string|number} value   数据值
 * @param {string} primaryKey     数据只要名称
 * @param {string} superiorKey    数据上级字段名称
 * @param {string} lowerKey       数据下级字段名
 */
export function getAllByValue(treeData, value, primaryKey = 'id', superiorKey = 'pid', lowerKey = 'children') {
    if (treeData.length === 0) return [];
    let unpack = unpackTreeData(treeData, lowerKey)
    let data = [];
    while (value > 0) {
        let status = false
        unpack.forEach(row => {
            if (row[primaryKey] === value) {
                data.unshift(value)
                value = row.pid
                status = true
            }
        })
        if (!status) return []
    }
    return data
}


/**
 * 通过任意级的一个值获取树形数据完label
 * @param {Array} treeData        tree数据
 * @param {string|number} value   数据值
 * @param {string} primaryKey     数据只要名称
 * @param {string} superiorKey    数据上级字段名称
 * @param {string} labelKey       数据label数据值
 * @param {string} lowerKey       数据下级字段名
 * @returns {*[]}
 */
export function getAllByLabel(treeData, value, primaryKey = 'id', superiorKey = 'pid', labelKey = 'name', lowerKey = 'children') {
    if (treeData.length === 0) return [];
    let unpack = unpackTreeData(treeData, lowerKey)
    let data = [];
    while (value > 0) {
        let status = false
        unpack.forEach(row => {
            if (row[primaryKey] === value) {
                data.unshift(row[labelKey])
                value = row[superiorKey]
                status = true
            }
        })
        if (!status) return []
    }
    return data
}